package com.ruoyi.basebill.task;


import com.ruoyi.basebill.domain.OmsReceiptbill;
import com.ruoyi.basebill.service.impl.OmsPurinwarehsbillServiceImpl;
import com.ruoyi.basebill.service.impl.OmsReceiptbillServiceImpl;
import com.ruoyi.basebill.service.impl.OmsSaleissuebillServiceImpl;
import com.ruoyi.basebill.task.util.OmsTaskUtil;
import com.ruoyi.basedata.domain.BdCustomer;
import com.ruoyi.basedata.domain.OmsOrgunit;
import com.ruoyi.basedata.service.impl.BdCustomerServiceImpl;
import com.ruoyi.basedata.service.impl.OmsOrgunitServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component("OmsReceiptBillTask")
public class OmsReceiptBillTask {

    //收货确认服务层接口
    @Autowired
    private OmsReceiptbillServiceImpl receiptbillService;

    //销售出库单服务层接口
    @Autowired
    private OmsSaleissuebillServiceImpl saleissuebillService;

    //采购入库单服务层接口
    @Autowired
    private OmsPurinwarehsbillServiceImpl purinwarehsbillService;

    //结算组织服务层接口
    @Autowired
    private OmsOrgunitServiceImpl orgunitService;

    //客户服务层接口
    @Autowired
    private BdCustomerServiceImpl customerService;

    //定时任务工具类
    @Autowired
    private OmsTaskUtil omsTaskUtil;

    //注入自己
    @Autowired
    private OmsReceiptBillTask receiptBillTask;

    public void pushDown() {
        List<OmsReceiptbill> omsReceiptbills = receiptbillService.selectPushDownBill();
        if (StringUtils.isEmpty(omsReceiptbills)) {
            return;
        }
        for (OmsReceiptbill receiptbill : omsReceiptbills) {
            OmsReceiptbill receiptbill1 = receiptBillTask.pushDownMethod(receiptbill);
            receiptbillService.updateOmsReceiptbill(receiptbill1);
        }


    }

    public void pushDownOut() {
        //处理重复单据
        omsTaskUtil.dealRepeatReceBill();
        List<OmsReceiptbill> omsReceiptbills = receiptbillService.selectPushDownOutSaleBill();
        if (StringUtils.isEmpty(omsReceiptbills)) {
            return;
        }
        for (OmsReceiptbill receiptbill : omsReceiptbills) {
            OmsReceiptbill omsReceiptbill1 = receiptBillTask.pushDownOutSaleBill(receiptbill);
            //此处需要修改原本的修改逻辑，不能将查出来的汇总后的分录覆盖原分录，只能修改表头
            receiptbillService.updateOmsReceiptbillHead(omsReceiptbill1);
        }
    }


    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public OmsReceiptbill pushDownMethod(OmsReceiptbill receiptbill) {
        try {
            //此处需要还原对象
            receiptbill = receiptbillService.selectOmsReceiptbillById(receiptbill.getId());
            StringBuffer stringBuffer = new StringBuffer();
            //空值校验判断
            int i1 = omsTaskUtil.JudgeNullValues(receiptbill, stringBuffer);
            if (i1 == 0) {
                //手动回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                receiptbill.setIscreatebill(-1L);
                receiptbill.setReason(stringBuffer.toString());
                return receiptbill;
            }
            String customercode = receiptbill.getCustomercode();
            BdCustomer bdCustomer = new BdCustomer();
            bdCustomer.setCustomernumber(customercode);
            List<BdCustomer> bdCustomers = customerService.selectBdCustomerList(bdCustomer);
            bdCustomer = bdCustomers.get(0);
            Long isinternal = bdCustomer.getIsinternal();
            Long iscostcenter = bdCustomer.getIscostcenter();
            //判断是否内部客户
            boolean isOutCustomer = isinternal.equals(0L) && iscostcenter.equals(0L);
            String invoicecode = receiptbill.getInvoicecode();
            //根据组织服务层接口获取销售组织数据
            OmsOrgunit invoiceUnit = new OmsOrgunit();
            invoiceUnit.setOrgnumber(invoicecode);
            List<OmsOrgunit> omsOrgunits = orgunitService.selectOmsOrgunitList(invoiceUnit);
            //将销售组织对象存储
            invoiceUnit = omsOrgunits.get(0);

            String inventoryorganizationcode = receiptbill.getInventoryorganizationcode();
            //根据组织服务层接口获取发货组织数据
            OmsOrgunit inventoryUnit = new OmsOrgunit();
            inventoryUnit.setOrgnumber(inventoryorganizationcode);
            omsOrgunits = orgunitService.selectOmsOrgunitList(inventoryUnit);
            //将发货组织对象存储
            inventoryUnit = omsOrgunits.get(0);
            //如果销出组织等于采入组织
            if (invoicecode.equals(inventoryorganizationcode)) {
                if (isinternal.equals(1L) || iscostcenter.equals(1L)) {
                    //生成一张库存调拨单
                    int i = omsTaskUtil.createFirstOrgSTBill(inventoryUnit, bdCustomer, receiptbill, stringBuffer);
                    if (i == 0) {
                        //手动回滚事务
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        receiptbill.setIscreatebill(-1L);
                        receiptbill.setReason(stringBuffer.toString());
                        return receiptbill;
                    }
                }

                receiptbill.setIscreatebill(1l);
                receiptbill.setReason("");
                return receiptbill;
            }



            //得到销售组织的一级组织，判断是否等于库存组织，如果不相等就需要生成对应一级组织之间的销出、采入单。
            if (!invoiceUnit.getFirstorgnumber().equals(inventoryorganizationcode)) {
                String firstorgnumber = invoiceUnit.getFirstorgnumber();
                OmsOrgunit firstOrg = new OmsOrgunit();
                firstOrg.setOrgnumber(firstorgnumber);
                List<OmsOrgunit> omsOrgunits1 = orgunitService.selectOmsOrgunitList(firstOrg);
                if (StringUtils.isEmpty(omsOrgunits1)) {
                    stringBuffer.append("[没有找到组织编号为：" + firstorgnumber + " 的组织]");
                    //手动回滚事务
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    receiptbill.setIscreatebill(-1L);
                    receiptbill.setReason(stringBuffer.toString());
                    return receiptbill;
                }
                firstOrg = omsOrgunits1.get(0);
                //生成对应的库存组织的销出和一级组织的采入单
                int i = omsTaskUtil.createFirstSIBillAndPWBill(inventoryUnit, firstOrg, receiptbill, bdCustomer, stringBuffer);
                if (i == 0) {
                    //手动回滚事务
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    receiptbill.setIscreatebill(-1L);
                    receiptbill.setReason(stringBuffer.toString());
                    return receiptbill;
                }
            }
            //判断销售组织是否是一级组织，不是则生成销售组织的一级组织到销售组织之间的销出采入单；是则跳过
            if (!invoiceUnit.getLevel().equals(1L)) {
            //准备一个集合，用来存储中间过度的组织,统一用于后续生成采入销出单
            //先获取销售组织的一级组织，记为firstOrg
            //再获取销售组织的上级组织，记为fatherOrg
            //开始循环,使用while循环,判断条件为firstOrg与fatherOrg是否相等
            //循环内容为：获取fatierOrg的上级组织，并将值赋值给
            //如果不相同则将fatherOrg加入到集合中
            //如果相等结束循环。
            //将一级组织生成销出单，销售组织生成采入单
            //过渡组织集合生成采入、销出单

            ArrayList<OmsOrgunit> transitionOrg = new ArrayList<>();
            String firstOrg = invoiceUnit.getFirstorgnumber();
            OmsOrgunit firstOrgUnit = new OmsOrgunit();
            firstOrgUnit.setOrgnumber(firstOrg);
            List<OmsOrgunit> firstOrgUnits = orgunitService.selectOmsOrgunitList(firstOrgUnit);
            if (StringUtils.isEmpty(firstOrgUnits)) {
                stringBuffer.append("[没有找到组织：" + firstOrg + "]");
                //手动回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                receiptbill.setIscreatebill(-1L);
                receiptbill.setReason(stringBuffer.toString());
                return receiptbill;
            }
            firstOrgUnit = firstOrgUnits.get(0);
            String parentorgnumber = invoiceUnit.getParentorgnumber();
            OmsOrgunit parentUnit = new OmsOrgunit();
            parentUnit.setOrgnumber(parentorgnumber);
            List<OmsOrgunit> omsOrgunits1 = orgunitService.selectOmsOrgunitList(parentUnit);
            if (StringUtils.isEmpty(omsOrgunits1)) {
                stringBuffer.append("[没有找到组织：" + parentorgnumber + "]");
                //手动回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                receiptbill.setIscreatebill(-1L);
                receiptbill.setReason(stringBuffer.toString());
                return receiptbill;
            }
            parentUnit = omsOrgunits1.get(0);
            while (!firstOrg.equals(parentorgnumber)) {
                transitionOrg.add(0, parentUnit);
                OmsOrgunit tempOrgUnit = new OmsOrgunit();
                tempOrgUnit.setOrgnumber(parentUnit.getParentorgnumber());
                List<OmsOrgunit> tempOrgUnits = orgunitService.selectOmsOrgunitList(tempOrgUnit);
                if (StringUtils.isEmpty(tempOrgUnits)) {
                    stringBuffer.append("[没有找到组织：" + tempOrgUnit.getOrgnumber() + "]");
                    //手动回滚事务
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    receiptbill.setIscreatebill(-1L);
                    receiptbill.setReason(stringBuffer.toString());
                    return receiptbill;
                }
                parentUnit = tempOrgUnits.get(0);
                parentorgnumber = parentUnit.getOrgnumber();
            }
            transitionOrg.add(0, firstOrgUnit);
            transitionOrg.add(invoiceUnit);
            //依次将两个组织传入方法进行生成销出采入单
            for (int i = 0; i < transitionOrg.size() - 1; i++) {
                int insertResult = omsTaskUtil.createTransitionSIBillAndPWBill(transitionOrg.get(i), transitionOrg.get(i + 1), receiptbill, bdCustomer, stringBuffer);
                if (insertResult == 0) {
                    //手动回滚事务
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    receiptbill.setIscreatebill(-1L);
                    receiptbill.setReason(stringBuffer.toString());
                    return receiptbill;
                }
            }
            }
            //如果是内部客户，销售组织的中转仓不等于收获仓，生成调拨单
            if (!isOutCustomer){
                String transferwhnumber = invoiceUnit.getTransferwhnumber();
                String receivefacilitycode = receiptbill.getReceivefacilitycode();
                if (!transferwhnumber.equals(receivefacilitycode)){
                    //生成一张调拨单，由中转仓调拨到收获仓
                    int insetResult = omsTaskUtil.createInvoiceUnitTransferBill(invoiceUnit, bdCustomer, receiptbill, stringBuffer);
                    if (insetResult == 0){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        receiptbill.setIscreatebill(-1L);
                        receiptbill.setReason(stringBuffer.toString());
                        return receiptbill;
                    }
                }
            }

            receiptbill.setIscreatebill(1l);
            receiptbill.setReason("");
            return receiptbill;
        } catch (Exception e) {
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            receiptbill.setIscreatebill(-1L);
            receiptbill.setReason(e.getMessage());
            return receiptbill;
        }
    }

    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public OmsReceiptbill pushDownOutSaleBill(OmsReceiptbill receiptbill) {
        //此处需要还原对象
        //此处需要修改还原对象的方法
//        receiptbill = receiptbillService.selectOmsReceiptbillById(receiptbill.getId());
        receiptbill = receiptbillService.selectOmsReceiptbillSummaryEntryById(receiptbill.getId());
        StringBuffer stringBuffer = new StringBuffer();
        //空值校验判断
        int i1 = omsTaskUtil.JudgeNullValues(receiptbill, stringBuffer);
        if (i1 == 0) {
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            receiptbill.setIscreateoutbill(-1L);
            receiptbill.setOutreason(stringBuffer.toString());
            return receiptbill;
        }
        String customercode = receiptbill.getCustomercode();
        BdCustomer bdCustomer = new BdCustomer();
        bdCustomer.setCustomernumber(customercode);
        List<BdCustomer> bdCustomers = customerService.selectBdCustomerList(bdCustomer);
        bdCustomer = bdCustomers.get(0);
        Long isinternal = bdCustomer.getIsinternal();
        Long iscostcenter = bdCustomer.getIscostcenter();
        boolean isOutCustomer = isinternal.equals(0L) && iscostcenter.equals(0L);
        if (isOutCustomer) {
            //生成一张对外的销售出库单
            int i = omsTaskUtil.createForeignSaleIssueBill(receiptbill, stringBuffer);
            if (i == 0) {
                //手动回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                receiptbill.setIscreateoutbill(-1L);
                receiptbill.setOutreason(stringBuffer.toString());
                return receiptbill;
            }
            receiptbill.setIscreateoutbill(1L);
            return receiptbill;
        }
        receiptbill.setIscreateoutbill(-2L);
        return receiptbill;
    }











}
